/*
 * Copyright 2011 evswork Team
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

package org.evswork.getwit.regexp;

import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class RegExpObject {
	Context ctxt;
	int pos;
	String data;
	int status;
	Pattern pattern;
	
	public final static int ERROR 	= 0;
	public final static int ENABLE 	= 1;
	public final static int DISABLE	= 2;
	
	public RegExpObject(Context ctxt,int pos) {
		this.ctxt = ctxt;
		this.pos = pos;
		load();
		if (status != ERROR && data.length()>0)
			pattern = Pattern.compile(data);
	}

	public void load() {
		SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(ctxt);
		status = pref.getInt(String.format("re_%d_sts", pos), DISABLE);
		data = pref.getString(String.format("re_%d_dat", pos), "");
	}
	
	public void save() {
		SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(ctxt);
		pref.edit()
			.putInt(String.format("re_%d_sts", pos), status)
			.putString(String.format("re_%d_dat", pos), data)
			.commit();
	}
	
	public void update(String exp) {
		data = exp;
		try {
			// just have a try
			pattern = Pattern.compile(exp);
			if (exp.length()>0)
				status = ENABLE;
			else
				status = DISABLE;
		} catch (PatternSyntaxException e) {
			pattern = null;
			status = ERROR;
		}
		save();
	}
	
	public void setEnable(boolean val) {
		if (ERROR == status) {
			return;
		}
		if (val) { // enable?
			status = (data.length() == 0)?DISABLE:ENABLE;
			if (data.length()==0)
				Log.d("Getwit","cannot enable,not allowed");
		} else {
			status = DISABLE;
		}
		save();
	}
}
